package com.lsongh.controller;

import com.lsongh.filter.LoginFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/6.
 */
@Controller
public class LoginController {
    @RequestMapping(value = "/")
    public  String index(@SessionAttribute(LoginFilter.SESSION_KEY) String username, Model model){
        model.addAttribute("name",username);
        return "index";
    }
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public  @ResponseBody String login(String username, String password, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        if (!"123456".equals(password)) {
            map.put("success", false);
            map.put("message", "密码错误");
            return map.toString().trim();
        }

        // 设置session
        session.setAttribute(LoginFilter.SESSION_KEY, username);

        map.put("success", true);
        map.put("message", "登录成功");
        return map.toString().trim();
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        // 移除session
        session.removeAttribute(LoginFilter.SESSION_KEY);
        return "redirect:/login";
    }
}
